<template>
  <div class="login">
    <div class="wrapper">
      <div class="welcome">登录</div>
      <div class="alertHint">
        <i class="el-icon-info"></i>
        <span>请登录后再继续浏览</span>
      </div>
      <form class="login-body" autocomplete="on">
        <table cellpadding="0" cellspacing="0">
          <tr>
            <td><label for="userName">账号：</label></td>
            <td>
              <input type="text" id="userName" v-model="loginInfo.userName" autofocus="autofocus"/>
            </td>
            <td>
              <i class="iconfont"></i>
              <span class="hint"></span>
            </td>
          </tr>

          <tr>
            <td><label for="passWord">密码：</label></td>
            <td>
              <input type="passWord" id="passWord" style="ime-mode:disabled" 
                v-model="loginInfo.passWord"
              />
            </td>
            <td>
              <i class="iconfont passWordIcon"></i>
              <span class="hint passWordHint"></span>
            </td>
          </tr>

          <tr>
            <td></td>
            <td class="choseTodo">
              <input type="checkbox" id="autoLogin"/>
              <label for="autoLogin" @click="autoLoginBtn">自动登陆</label>
              <span class="reFind">找回密码</span>
            </td>
            <td> </td>
          </tr>

          <tr>
            <td> </td>
            <td class="loginButton">
              <div class="commit" @click="postAllLoginInfo">登录</div>
            </td>
            <td> </td>
          </tr>

        </table>
      </form>
      <!-- 侧边栏 -->
      <div class="aside">
        <div class="intro">
          <div class="intro-text">还没有账号？</div>
          <router-link tag="div" to="/regist">
            <div class="intro-btn">立即注册</div>
          </router-link>
        </div>
      </div>

      <alert-prop 
      v-if="showAlert" 
      :fromText="'登陆'" 
      :toText="'首'" 
      :toRoute="'/home'">
    </alert-prop>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { http } from 'common/verify.js';
import { mapMutations } from 'vuex';
import AlertProp from 'common/alert/AlertProp.vue';
export default {
  name: 'Login',
  inject: ['reload'],
  components: {
    AlertProp
  },
  data () {
    return {
      loginInfo: {
        userName: '',
        passWord: '',
      },
      autoLogin: false,
      showAlert: false,
      //顺序分别是borderColor,trColor,iconCode,iconColor,hintColor
      inputStyle: {
        focusStyle:['#99d8f5','#eff7fe','&#xe6b7;','#ccc','#999'],
        blurStyle:['#ccc','#fff','&#xe6b7;','#fff','#fff'],
        errorStyle:['#ccc','#fff','&#xe600;','#ec2716','#b52828']
      },
      hintText: {
        userName: {
          focus: '用户名',
          void: '用户名不能为空',
          error: '账号不存在'
        },
        passWord: {
          focus: '密码',
          void: '密码不能为空',
          error: '密码输入错误'
        }
      },
      responseData: ''
    }
  },
  mounted () {
    this.handleFocusChange();
    this.handleBlurChange();
  },
  methods: {
    autoLoginBtn(){
      if (this.autoLogin) {
        this.autoLogin = false
      }else{
        this.autoLogin = true
      }
    },
    handleFocusChange () {
      const _this = this;//important
      $('#userName').on('focus',function(){
        focusChange($(this));
      });
      $('#passWord').on('focus',function(){
        focusChange($(this));
      });
      function focusChange(el){
        const hint = el.parent().next().children('span');
        const id = el.attr('id');
        //统一：边框颜色变化、父元素背景色、图标、提示文字变更
        _this.inputStyleChange(el,_this.inputStyle.focusStyle);
        hint.text(_this.hintText[id].focus);
      }
    },
    handleBlurChange () {
      var _this = this;//important
      $('#userName').on('blur', function(){
        blurChange($(this))
      });
      $('#passWord').on('blur', function(){
        blurChange($(this))
      });
        
      function blurChange(el) {
        //失去焦点的样式：边框和tr背景取消
        _this.inputStyleChange(el,_this.inputStyle.blurStyle);
        //定义经常用到的变量
        const val = el.val();
        const len = el.val().length;
        const trimVal = val.replace(/\s/g,"");
        const id = el.attr('id');
        const hint = el.parent().next().children('span');
        if (len == 0 || trimVal == '') {
          //当没有输入任何字符或输入字符为全空格，显示错误
          _this.inputStyleChange(el,_this.inputStyle.errorStyle);
          hint.text(_this.hintText[id].void);
        }else{
          hint.text('');
        }
      }
    },
    inputStyleChange (el,[borderColor,trColor,iconCode,iconColor,hintColor]) {
      //定义必须常量
      const hint = el.parent().next().children('span');
      const icon = el.parent().next().children('i');
      const tr = el.parent().parent();
      //改变input焦点获取、失去焦点、输入错误、输入正确等样式
      el.css({ 'border': '1px solid '+borderColor+''});
      tr.css({ 'background': ''+trColor+''});
      icon.html(''+iconCode+'').css({'color': ''+iconColor+''});
      hint.css({'color':''+hintColor+''});
    },
    postAllLoginInfo () {
      var succ = true;
      const _this = this;
      //检测内容是否为空，为空则不接下去执行，icon图标是否为正确，不是则不接下去执行
      if ($('#userName').val() == '') hintForVoid ($('#userName'));
      if ($('#passWord').val() == '') hintForVoid ($('#passWord'));

      function hintForVoid (el) {
        const hint = el.parent().next().children('span');
        const id = el.attr('id');
        _this.inputStyleChange(el,_this.inputStyle.errorStyle);
        hint.text(_this.hintText[id].void);
        succ = false
      }

      //传数据
      if (succ === true) {
        const loginData = _this.loginInfo
        //将数据转换成你要的样子
        const finaldata = JSON.stringify(loginData);
        axios({
          method: 'post',
          url: ''+http+':8080/user/login',
          headers:{
            'token': 'data',
            'Content-type': 'application/json'
          },
          data: finaldata
        }).then(function (response) {
          console.log(response)
        　if(response.data.code== 0) {
            _this.responseData = response.data.data;
            window.localStorage.setItem('responseData', _this.responseData);
            _this.handleUsernameOcur();
            _this.showAlert = true;
            setTimeout(function() {
              _this.$store.commit('changeUsername',_this.loginInfo.userName);
              _this.showAlert = false;
              location.reload()
              _this.$router.push('/home');
            },5000)
            
          }else {
            _this.inputStyleChange($('#userName'),_this.inputStyle.errorStyle);
            const hint = $('#userName').parent().next().children('span');
            hint.text(response.data.msg);
          }
        }).catch(function (error) {
        　console.log(error);
        })
      }
    },
    handleUsernameOcur(){
      //页面初始化时，如果帐号密码cookie存在则填充
      if(getCookie('userName') && getCookie('passWord')){
        oUser.value = getCookie('userName');
        oPswd.value = getCookie('passWord');
        this.autoLogin = true;
      };
      //复选框勾选状态发生改变时，如果未勾选则清除cookie
      if(!this.autoLogin){
          delCookie('userName');
          delCookie('passWord');
      };
      //表单提交事件触发时，如果复选框是勾选状态则保存cookie
      if(this.autoLogin){
        setCookie('userName',oUser.value,7); //保存帐号到cookie，有效期7天
        setCookie('passWord',oPswd.value,7); //保存密码到cookie，有效期7天
      };
      //设置cookie
      function setCookie(name,value,day){
        var date = new Date();
        date.setDate(date.getDate() + day);
        document.cookie = name + '=' + value + ';expires='+ date;
      };
      //获取cookie
      function getCookie(name){
        var reg = RegExp(name+'=([^;]+)');
        var arr = document.cookie.match(reg);
        if(arr){
          return arr[1];
        }else{
          return '';
        }
      };
      //删除cookie
      function delCookie(name){
        setCookie(name,null,-1);
      };
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~assets/css/mixins.styl';
  input:nth-child(1),input:nth-child(2)
    width: 4.47rem
    height: .56rem
    border: 1px solid #ccc
    margin-left: .45rem
  td
    padding: .36rem 0
  table tr td:nth-child(1)
    width: 2.54rem
    text-align: right
  table tr td:nth-child(2)
    width: 4.5rem
    text-align: left
  table tr td:nth-child(3)
    width: 6rem
  .login
    container()
    padding-top: $spaceHeight
    .wrapper
      wrapper()
      .welcome
        width: 100%
        padding: .3rem 0 .3rem .3rem
        font-size: .32rem
        font-weight: bold
        font-family: 'Microsoft YaHei'
        color: $font-welcome
        border: 1px solid $bgcolor-all
      .alertHint
        margin: .5rem 5rem .3rem .4rem
        background: #ffffe9
        border: .02px solid #faebd2
        padding: .2rem 0 .2rem .1rem
        font-size: .26rem
        .el-icon-info
          color: #4e97ce
          font-size: .28rem
        span 
          color: #666
      .login-body
        padding: 0 .3rem
        width: 14rem
        padding-bottom: .9rem
        .iconfont
          vertical-align: middle
        .hint
          font-size: .24rem
        .choseTodo
          font-size: .24rem
          position: relative
          input
            width: .25rem
            height: .25rem
          .reFind
            color: $font-blue
            position: absolute
            right: .5rem
          .reFind:hover
            text-decoration: underline
            cursor: pointer
        .commit
          width: 1.6rem
          line-height: .64rem
          margin-left: .3rem
          text-align: center
          color: $bgcolor-white
          background: linear-gradient(to bottom, #50a1d3 , #0c497c)
          border: .01rem solid #438cf9
          border-radius: .06rem
        .commit:hover
          cursor: pointer
          background: linear-gradient(to bottom, #458ecb , #0c497c) 
      .aside
        position: absolute
        right: 2rem
        top: 1.4rem
        border-left: .03rem dotted $borderColor
        .intro
          margin: .3rem 0 .5rem .5rem
          .intro-text
            font-size: .24rem
            color: $font-black
            margin-bottom: .2rem
          .intro-btn
            font-size: .28rem
            color: $font-black
            width: 1.88rem
            height: .62rem
            line-height: .62rem
            text-align: center
            padding: .2rem auto
            background: linear-gradient(to bottom, $bgcolor-white , #e9e9e9)
            border: .02rem solid $borderColor
            border-radius: .08rem
          .intro-btn:hover
            color: $font-black
            background: linear-gradient(to bottom, #fbfbfb , $borderColor)
            cursor: pointer
</style>